package org.example;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {
    @Autowired
    private Producer producer;

    @PostMapping("/login")
    @ResponseBody
    public String login(String name, String password, String code, HttpSession session){
        if (code.equals(session.getAttribute("code"))){
            return "ok";
        }else {
            return "error";
        }
    }

    @GetMapping("/kaptcha")
    public void kaptcha(HttpServletResponse response,HttpSession session) throws IOException {
        String text = producer.createText();
        System.out.println("text = " + text);
        session.setAttribute("code",text);
        response.setContentType("image/png");
        ImageIO.write(producer.createImage(text),"png",response.getOutputStream());

    }
}
